<?php

namespace app\models;

use yii;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
use yii\data\Pagination;
use yii\data\ActiveDataProvider;
use yii\db\Expression;
use app\common\Functions;



class ProdInstSearch extends ProdInst
{

    public $region_name;
    public $user_name;
    public $content;
    public $sub_staff_group;//片区
    public $affiliation;
    public $prod_trading_area;//商圈
    public $renovation_flag;
    public $early_warning;
    public $floor_height;
    public $investment_flag;
    public $month_fee;
    public $fee;
    public $gonwei;
    public $transfer;
    public $payment;
    public $equipment;
    public $register;
    public $prod_context;
    public $area;
    public $number;
    public $floor;


    public static function tableName()
    {
        return ProdInst::tableName();
    }

    public function rules()
    {
        return [
            [['region_id'], 'safe'],
            [['region_name'], 'safe'],
            [['prod_name'], 'safe'],
            [['user_name'], 'safe'],
            [['own_cust_name'], 'safe'],
            [['state'], 'safe'],
            [['content'], 'safe'],
            [['sub_staff_group'], 'safe'],//片区
            [['affiliation'], 'safe'],//人员
            [['state'], 'safe'],
            [['renovation_flag'], 'safe'],//装修
            [['early_warning'], 'safe'],
            [['floor_height'], 'safe'],
            [['investment_flag'], 'safe'],
            [['month_fee'], 'safe'],
            [['fee'], 'safe'],
            [['gonwei'], 'safe'],
            [['transfer'], 'safe'],
            [['payment'], 'safe'],
            [['equipment'], 'safe'],
            [['register'], 'safe'],
            [['prod_context'], 'safe'],
            [['area'], 'safe'],
            [['number'], 'safe'],
            [['floor'], 'safe'],
            [['staff_id'], 'safe'],
            [['file'], 'safe'],

        ];
    }
//    public function search($params, $prod_spec_id=null)
//    {
//
//    }

    public function search($params, $prod_spec_id=null, $parent_id=null, $own_cust_id=null ,$commonality=null ,$state=null ,$set=null,$queryWhere=null)
    {
        $query = ProdInst::find()->alias('a');//(产品实例表
        $query->joinWith('users  AS f');//User表 ID
        $query->joinWith('regions  AS b');//Region 表（地区
        $query->joinWith('parentRegions  AS c');//Region

        // 加入合同查询
        $query->joinWith('contracts  AS ct');//Contract






        // 如果是楼盘需要取出子集
//        if ($prod_spec_id==10001) // 楼盘下挂房源
//        {
//            $query->joinWith('subProdInsts  AS l');
//
//        }
//        else if($prod_spec_id==10002) // 房源找楼盘
//        {
//            $query->joinWith('parentProdInsts  AS m');
//
//
//        }

        //$query->joinWith('prodAttrInsts  AS e');
        $query->joinWith('custs  AS n');//客户表

        $query->joinWith('useStaffs  AS z');///*Staff表的user_id*/


        //$query->joinWith('prodAttrInststf  AS tf');//prod_attr_inst表(转让费 80)
        //$query->joinWith('prodAttrInstsems  AS em');//prod_attr_inst表（设备 79）

        if ($queryWhere)
        {
            if ($queryWhere['template']=='prod') {

                $query->joinWith('prodAttrInstsetl  AS tl'); //prod_attr_inst表（门牌号 4）
            }
        }




        //  如果定义查询有值,则检查输入的查询字段

        if($queryWhere['group'] ==1){
            $where['z.staff_group'] = 1;
        }

        if ($own_cust_id)
        {
            $where['a.own_cust_id'] = $own_cust_id;
        }

        if ($state)
        {
            $where['a.state'] = $state;
        }
        if ($set)//我开发的房源
        {
            $where['a.create_staff_id'] = $set;
        }

        if ($parent_id!=null)
        {
            $where['a.parent_id'] = $parent_id;

        }
        else
        {
            $where['a.prod_spec_id'] = $prod_spec_id;
            if($commonality != null){
                    $where['a.commonality'] = $commonality;
                    //按照-1的条件找所有公共的房源(房源在谁名下)

            }

        }



        $query->where($where);

        if($queryWhere['template']=='prod'){
            $query->orderBy(['tl.content'=> SORT_ASC]);

        }else{
            $query->orderBy(['a.modify_date'=> SORT_DESC]);
        }

      //  $query->all();
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 50,
            ],
        ]);


        $sort = $dataProvider->getSort(); // 获取yii自动生成的排序规则
        $sort->attributes['region_name'] = [ // 添加用户名的排序规则
            'asc' => ['b.region_name' => SORT_ASC],
            'desc' => ['b.region_name' => SORT_DESC],
        ];


//        $sort->attributes['prod_name'] = [ // 添加用户名的排序规则
//            'asc' => ['a.prod_name' => SORT_ASC],
//            'desc' => ['a.prod_name' => SORT_DESC],
//        ];

        $dataProvider->setSort($sort);


        if ($queryWhere)
        {
            if ($queryWhere['out_time']) {

                $day=Functions::getWeekend();
                $whereLeft = new Expression("DATE_SUB(now(),INTERVAL 4 + ".$day." DAY)");
                $query->andFilterWhere(['<', 'a.modify_date',$whereLeft]);


            }

            // 小组长
            if ($queryWhere['sub_staff_group'])
            {

                $query->andFilterWhere(['=', 'z.sub_staff_group',$queryWhere['sub_staff_group']]);

            }

            // 主管
            if ($queryWhere['staff_group']  )
            {
                $query->andFilterWhere(['=', 'z.staff_group',$queryWhere['staff_group']]);

            }
        }



        if (!($this->load($params) )) {
            return $dataProvider;
        }




//&& $this->validate()
//        if (!($this->load($params) )) {
//            return $dataProvider;
//        }

        if(!empty($this->renovation_flag)){
            $query->joinWith('prodAttrInstsd  AS g');//prod_attr_inst表
        }
        if(!empty($this->area)){
            $query->joinWith('prodAttrInstsh  AS h');//prod_attr_inst表
        }
        if(!empty($this->month_fee)){
            $query->joinWith('prodAttrInstsj  AS j');//prod_attr_inst表
        }
        if(!empty($this->fee)){
            $query->joinWith('prodAttrInstsk  AS k');//prod_attr_inst表
        }
        if(!empty($this->floor_height)){
            $query->joinWith('prodAttrInstsl  AS l');//prod_attr_inst表
        }
        if(!empty($this->investment_flag)){
            $query->joinWith('prodAttrInstsm  AS m');//prod_attr_inst表
        }
        if(!empty($this->gonwei)){
            $query->joinWith('prodAttrInstgw  AS gw');//prod_attr_inst表
        }
//        if(!empty($this->transfer)){
//            $query->joinWith('prodAttrInststf  AS tf');//prod_attr_inst表
//        }
        if(!empty($this->payment)){
            $query->joinWith('prodAttrInstspm  AS pm');//prod_attr_inst表
        }
//        if(!empty($this->equipment)){
//            $query->joinWith('prodAttrInstsem  AS em');//prod_attr_inst表
//        }
        if(!empty($this->register)){
            $query->joinWith('prodAttrInstsrs  AS rs');//prod_attr_inst表
        }
        if(!empty($this->prod_context)){
            $query->joinWith('prodAttrInstspc  AS pc');//prod_attr_inst表
        }



        //一条分割线-------------------------------------------







//        if(!empty($this->early_warning)){
//
//            $date= time();//取出当前时间
//            $time=$this->early_warning*3600*24;//天数转时间戳
//            $times=$date-$time;
//
//            $query->andFilterWhere(['<', 'input_time', 'DATE_SUB(now(),INTERVAL 2 DAY)']);
//            //$query->andFilterWhere(['like', 'a.modify_date', date('Y-m-d',$times)]); //天数
//        }

        $query->andFilterWhere(['=', 'a.region_id', $this->region_id]);
        $query->andFilterWhere(['like', 'a.prod_name', $this->prod_name]);
        $query->andFilterWhere(['like', 'b.region_name', $this->region_name]);
        $query->andFilterWhere(['like', 'f.username', $this->user_name]);
        $query->andFilterWhere(['like', 'n.own_cust_name', $this->ownCustName]);
        $query->andFilterWhere(['=', 'a.state', $this->state]);

        $query->andFilterWhere(['=', 'z.sub_staff_group', $this->sub_staff_group]);//片区
        $query->andFilterWhere(['=', 'z.user_id', $this->affiliation]);//人员
        if(!empty($this->renovation_flag)){
            $query->andFilterWhere(['=', 'g.attr_spec_id', 25 ])
                ->andFilterWhere(['=', 'g.content', $this->renovation_flag]);//装修
        }
        if(!empty($this->area)){
            $check =strpos($this->area, '-');
            if($check !== false){
                $sum=explode('-', $this->area);
                $query->andFilterWhere(['=', 'h.attr_spec_id', 8])
                    ->andFilterWhere(['>=', 'h.content', (int)$sum[0] ])
                    ->andFilterWhere(['<=', 'h.content', (int)$sum[1] ]); //建筑面积
            }else{
                $query->andFilterWhere(['=', 'h.attr_spec_id', 8])
                    ->andFilterWhere(['=', 'h.content', $this->area]); //建筑面积
            }

        }
        if(!empty($this->month_fee)){
            $check =strpos($this->month_fee, '-');
            if($check !== false){
                $sum=explode('-', $this->month_fee);
                $query->andFilterWhere(['=', 'j.attr_spec_id', 41])
                    ->andFilterWhere(['>=', 'j.content', (int)$sum[0]])
                    ->andFilterWhere(['<=', 'j.content', (int)$sum[1] ]);
            }else{
                $query->andFilterWhere(['=', 'j.attr_spec_id', 41])
                    ->andFilterWhere(['=', 'j.content', $this->month_fee]); //月租金
            }

        }
        if(!empty($this->fee)){
            $check =strpos($this->fee, '-');
            if($check !== false){
                $sum=explode('-', $this->fee);
                $query->andFilterWhere(['=', 'k.attr_spec_id', 7])
                    ->andFilterWhere(['>=', 'k.content', (int)$sum[0]]) //元/㎡
                    ->andFilterWhere(['<=', 'k.content', (int)$sum[1] ]);
            }else{
                $query->andFilterWhere(['=', 'k.attr_spec_id', 7])
                    ->andFilterWhere(['like', 'k.content', $this->fee]); //元/㎡
            }

        }
        if(!empty($this->floor_height)){
            $query->andFilterWhere(['=', 'l.attr_spec_id', 81])
                ->andFilterWhere(['=', 'l.content', $this->floor_height]); //高中低楼层
        }
        if(!empty($this->investment_flag)){
            $query->andFilterWhere(['=', 'm.attr_spec_id', 9])
                ->andFilterWhere(['=', 'm.content', $this->investment_flag]); //能否招商
        }
        if(!empty($this->gonwei)){
            $query->andFilterWhere(['=', 'gw.attr_spec_id', 53])
                ->andFilterWhere(['=', 'gw.content', $this->gonwei]); //工位数
        }
//        if(!empty($this->transfer)){
//            //$where = new Expression("to_int(tf.content)");//转成数字
//            $query->andFilterWhere(['=', 'tf.attr_spec_id', 80])
//                ->andFilterWhere(['>=', 'tf.content', (int)$this->transfer]); //转让费
//
//        }
        if(!empty($this->payment)){
            $query->andFilterWhere(['=', 'pm.attr_spec_id', 50])
                ->andFilterWhere(['like', 'pm.content', $this->payment]); //付款方式
        }
//        if(!empty($this->equipment)){
//            $query->andFilterWhere(['=', 'em.attr_spec_id', 79])
//                ->andFilterWhere(['like', 'em.content', $this->equipment]); //设备
//        }
        if(!empty($this->register)){
            $query->andFilterWhere(['=', 'rs.attr_spec_id', 49])
                ->andFilterWhere(['=', 'rs.content', $this->register]); //注册
        }
        if(!empty($this->prod_context)){
            $query->andFilterWhere(['=', 'pc.attr_spec_id', 5])
                ->andFilterWhere(['like', 'pc.content', $this->prod_context]); //房源描述
        }




        return $dataProvider;

//        $dataProvider->setSort([
//            'attributes' => [
//                /* 其它字段不要动 */
//                /*  下面这段是加入的 */
//                /*=============*/
//                'customer_name' => [
//                    'asc' => ['customer.customer_name' => SORT_ASC],
//                    'desc' => ['customer.customer_name' => SORT_DESC],
//                    'label' => 'Customer Name'
//                ],
//                /*=============*/
//            ]
//        ]);
    }




}

?>
